package com.wing.order.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.Result;
import com.wing.order.model.entity.OrderDelivery;
import com.wing.order.model.request.OrderDeliveryForm;
import com.wing.order.model.response.OrderDeliveryDetailVO;
import com.wing.order.model.response.OrderDeliveryVO;
import com.wing.order.model.response.ScanDeliveryVo;
import com.wing.order.service.OrderDeliveryService;
import com.wing.platform.feign.PlatformClient;
import com.wing.platform.order.model.entity.OrderDistributionLabel;
import com.wing.platform.order.model.response.OrderDistributionLabelVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-配送管理", tags = "#/order/orderDelivery")
@RestController("orderDeliveryController")
@RequestMapping("order/admin/orderDelivery")
@RequiredArgsConstructor
public class OrderDeliveryController {

    private final OrderDeliveryService orderDeliveryService;
    private final PlatformClient platformClient;

    @Value("${platform.gatewayUrl}")
    private String gatewayUrl;

    @ApiOperation(value = "查询签收任务列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "deliveryOrderCode", value="配送单编号", dataType = "String", paramType = "query")

    })

    @GetMapping("/getOrderDeliveryVOList")
    public PageResult<com.wing.platform.order.model.response.OrderDeliveryVO> getOrderDeliveryVOList(@RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , @RequestParam(required = false) String deliveryOrderCode
            , @RequestParam(required = false) String distCode
            , @RequestParam(required = false) String startCreateTime
            , @RequestParam(required = false) String endCreateTime

    ) {
        PageResult<com.wing.platform.order.model.response.OrderDeliveryVO> list = platformClient.getOrderDeliveryVOList(page, limit, sort, order
                , deliveryOrderCode,distCode,startCreateTime,endCreateTime);

        return new PageResult<>(list.getData(),list.getCount());
    }
    @ApiOperation(value = "签收任务列表详情配送物资信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryId", value = "配送订单id", defaultValue = "", example = "",required = true, dataType = "Long", paramType = "query")

    })
    @GetMapping("/getOrderDeliveryDetailVOList")
    public JsonResult<List<com.wing.platform.order.model.response.OrderDeliveryDetailVO>> getOrderDeliveryDetailVOList(
            @RequestParam(value = "deliveryId",required = true) Long deliveryId

    ){
        JsonResult<List<com.wing.platform.order.model.response.OrderDeliveryDetailVO>> jsonResult = platformClient.getOrderDeliveryDetailVOList(deliveryId);
        return JsonResult.success(jsonResult.getData());
    }

    @ApiOperation(value = "签收任务列表扫描包装编码", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "packLabelCode", value = "包装编码", defaultValue = "", example = "",required = true, dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "deliveryId", value = "配送订单id", defaultValue = "", example = "",required = true, dataType = "Long", paramType = "query")

    })
    @GetMapping("/getOrderDistributionLabelVOByCode")
    public JsonResult<OrderDistributionLabelVO> getOrderDistributionLabelVOByCode(
            @RequestParam(value = "packLabelCode",required = true) String packLabelCode
            ,@RequestParam(value = "deliveryId",required = true) Long deliveryId

    ){
        JsonResult<OrderDistributionLabelVO> jsonResult = platformClient.getOrderDistributionLabelVOByCode(packLabelCode,deliveryId);
        if (jsonResult.getCode() == Result.Code.SUCCESS.getCode()) {
            if(jsonResult.getData().getStatus().getValue() == 2){
                return JsonResult.fail("此包装条码已签收");
            }
            jsonResult.getData().setStatus(OrderDistributionLabel.Status.creation);
            return JsonResult.success(jsonResult.getData());
        }else{
            return JsonResult.fail("未找到包装条码");
        }
    }

    @ApiOperation(value = "查询签收任务产品已签收的包装条码", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryDetailId", value = "配送订单详情id", defaultValue = "", example = "",required = true, dataType = "Long", paramType = "query")

    })
    @GetMapping("/getProductPackLabelSign")
    public JsonResult<OrderDistributionLabelVO> getProductPackLabelSign(
            @RequestParam(value = "deliveryDetailId",required = true) Long deliveryDetailId

    ){
        JsonResult<List<OrderDistributionLabelVO>> jsonResult = platformClient.getProductPackLabelSign(deliveryDetailId);
        if (jsonResult.getCode() == Result.Code.SUCCESS.getCode()) {
            return JsonResult.success(jsonResult.getData());
        }else{
            return JsonResult.fail("此产品还未签收包装条码");
        }
    }

    @ApiOperation(value = "签收包装条码", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "signList", value="签收数据", dataType = "List",  required = true,paramType = "query")
    })
    @PostMapping("/deliverySign")
    public JsonResult deliverySign(@RequestBody List<OrderDistributionLabelVO> signList){
        try {
            orderDeliveryService.deliverySign(signList);
            return JsonResult.success("签收成功");
        }catch (Exception e){
            log.error("delivery fail",e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "查询所有配送", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OrderDelivery> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
    ){

        Page<OrderDelivery> pg = new Page<>(page, limit);
        QueryWrapper<OrderDelivery> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索

        IPage<OrderDelivery> list = orderDeliveryService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加配送", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(OrderDeliveryForm.Add.class) OrderDeliveryForm orderDeliveryForm) {
        if (orderDeliveryService.add(orderDeliveryForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改配送", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(OrderDeliveryForm.Update.class) OrderDeliveryForm orderDeliveryForm) {
        OrderDelivery orderDelivery = orderDeliveryService.getById(orderDeliveryForm.getId());
        if(orderDelivery == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OrderDelivery.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderDeliveryForm, orderDelivery, copyOptions);
        if (orderDeliveryService.updateById(orderDelivery)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除配送", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderDeliveryId", value = "配送id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long orderDeliveryId) {
        if (orderDeliveryService.removeById(orderDeliveryId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "签收任务", notes = "列表")
    @GetMapping("/signList")
    public PageResult<OrderDelivery> signList(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order) throws Exception {

        String reqUri = gatewayUrl + "platformCab/order/admin/orderDelivery/list";
        String reqNewUri = reqUri.concat("?page=").concat(page.toString()).concat("&limit=").concat(limit.toString())
                .concat("&sort=").concat(sort).concat("&order=").concat(order);
        //发送请求
        //请求
        String jsonInfo = HttpHelper.httpGet(reqNewUri);
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        //拿到数据
        JSONArray array = obj.getJSONArray("data");

        String js = JSON.toJSONString(array, SerializerFeature.WriteClassName);
        //转换成集合
        List<OrderDelivery> list = JSON.parseObject(js, List.class);
        return new PageResult(list, obj.getInteger("count"));
    }


    /**
     * 签收任务  调用平台端数据获取
     *
     * @param companyName 公司名稱 搜索
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "签收任务列表", notes = "查询")
    @GetMapping("/getSignInfo")
    public PageResult<OrderDeliveryVO> getSign(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , @RequestParam(required = false) String companyName
    ) throws Exception {

        //访问路径
        String reqUri = gatewayUrl + "platformCab/order/app/orderDelivery/getSignInfo";

        //转换成字符串
        String newPage = Integer.toString(page);
        String newLimit = Integer.toString(limit);

        String reqNewUri = reqUri.concat("?page=").concat(newPage).concat("&limit=").concat(newLimit)
                .concat("&sort=").concat(sort).concat("&order=").concat(order);

        if (StringUtils.isNotBlank(companyName)) {
            reqNewUri = reqUri.concat("?page=").concat(newPage).concat("&limit=").concat(newLimit)
                    .concat("&sort=").concat(sort).concat("&order=").concat(order)
                    .concat("&companyName=").concat(companyName);
        }
        //发送请求
        String jsonInfo = HttpHelper.httpGet(reqNewUri);
        //将平台端的json转换成List  因里面有别的数据，而我们需要的对象集合存在data，取键拿出
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        JSONArray arr = obj.getJSONArray("data");
        String js = JSON.toJSONString(arr, SerializerFeature.WriteClassName);
        //转换成集合
        List<OrderDeliveryVO> orderDeliveryList = JSON.parseObject(js, List.class);

        return new PageResult(orderDeliveryList, obj.getInteger("count"));
    }

    /**
     * 根据id查询配送对象
     */
    @ApiOperation(value = "根据id查询配送对象", notes = "查询")
    @GetMapping("/getDeliveryId")
    public JsonResult<OrderDelivery> getDeliveryId(@RequestParam("id") String id) throws Exception {
        String reqUri = gatewayUrl + "platformCab/order/admin/orderDelivery/getDeliveryId";
        String reqNewUri = reqUri.concat("?id=").concat(id);
        String jsonInfo = HttpHelper.httpGet(reqNewUri);
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        Object data = obj.get("data");
        return JsonResult.success(data);
    }

    /**
     * 详情
     */
    @GetMapping("/getDetail")
    public JsonResult<OrderDelivery> getDetail(@RequestParam String deliveryOrderCode){
        JSONObject detail = platformClient.getDetail(deliveryOrderCode);
        //拿到数据
        JSONArray array = detail.getJSONArray("data");

        String js = JSON.toJSONString(array, SerializerFeature.WriteClassName);
        //转换成集合
        List<OrderDelivery> list = JSON.parseObject(js, List.class);

        return JsonResult.success(list);
    }

    /**
     * 配送物资  /签收订单信息
     * @param deliveryOrderCode 配送单编号
     * @return
     */
    @GetMapping("/orderInfo")
    public JsonResult orderInfo(@RequestParam String deliveryOrderCode) throws Exception {

        //访问路径
        String reqUri = gatewayUrl + "platformCab/order/app/orderDelivery/orderInfo";
        final String newUri = reqUri.concat("?deliveryOrderCode=").concat(deliveryOrderCode);
        //请求
        String jsonInfo = HttpHelper.httpGet(newUri);
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        //拿到数据
        JSONArray array = obj.getJSONArray("data");

        String js = JSON.toJSONString(array, SerializerFeature.WriteClassName);
        //转换成集合
        List<OrderDeliveryDetailVO> list = JSON.parseObject(js, List.class);

        return JsonResult.success(list);
    }

    /**
     * 配送物资信息
     */
/*    @ApiOperation(value = "配送物资信息", notes = "查询")
    @GetMapping("/getDeliveryInfo")
    public JsonResult<OrderDeliveryVO> getDeliveryInfo(@RequestParam("deliveryOrderCode") String deliveryOrderCode) throws Exception {
        String reqUri = gatewayUrl + "platformCab/order/admin/orderDelivery/getDeliveryInfo";
        String newReqUrl = reqUri.concat("?deliveryOrderCode=").concat(deliveryOrderCode);
        String jsonInfo = HttpHelper.httpGet(newReqUrl);
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        Object data = obj.get("data");
        return JsonResult.success(data);
    }*/

    /**
     * 签收
     * @param packLabelCode     包装码
     * @param realReceive       实收数量
     * @param deliveryOrderCode 签收单号
     * @param abnormalNum       异常数
     */
    @GetMapping("/scanSign")
    public JsonResult scanSign(@RequestParam("packLabelCode") String packLabelCode,
                               @RequestParam("realReceive") Integer realReceive,
                               @RequestParam("deliveryOrderCode") String deliveryOrderCode,
                               @RequestParam(value = "remark", required = false) String remark,
                               @RequestParam("abnormalNum") Long abnormalNum) throws Exception {
        //调用平台端
        JSONObject jsonInfo = platformClient.backstageScanSign(packLabelCode, realReceive, deliveryOrderCode, abnormalNum);
        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap<String, Object>) jsonInfo.get("data");
        if (linkedHashMap.size() == 0) {
            return JsonResult.fail("签收数量大于应收数量,或已被扫描过");
        }
        JSONObject object = JSONObject.parseObject(String.valueOf(jsonInfo));
        JSONObject deliveryDetailVO = object.getJSONObject("data");
        //判断该批次是否已签收
        String reqUri = gatewayUrl + "platformCab/order/app/orderDelivery/orderInfo";
        final String newUri = reqUri.concat("?deliveryOrderCode=").concat(deliveryOrderCode);
        String jsonInfo2 = HttpHelper.httpGet(newUri);
        JSONObject obj = JSONObject.parseObject(jsonInfo2);
        JSONArray array = obj.getJSONArray("data");
        String js = JSON.toJSONString(array, SerializerFeature.WriteClassName);
        List<OrderDeliveryDetailVO> list = JSON.parseObject(js, List.class);
        //同步平台端数据
        if (list.size() == 0) {
            JSONObject jsonObject = platformClient.getScanInfo(deliveryOrderCode);
            JSONArray arr = jsonObject.getJSONArray("data");
            List<ScanDeliveryVo> deliveryVOList = arr.toJavaList(ScanDeliveryVo.class);
            orderDeliveryService.syncStorage(deliveryVOList, remark);
        }
        return JsonResult.success(deliveryDetailVO);
    }

    /**
     * 已签收详情列表
     */
    @GetMapping("/infoSign")
    public JsonResult<OrderDeliveryVO> infoSign(@RequestParam("deliveryOrderCode") String deliveryOrderCode) {
        List<OrderDeliveryVO> vo = orderDeliveryService.infoSign(deliveryOrderCode);
        return JsonResult.success(vo);
    }

    /**
     * 根据包装条码带出产品信息
     * @param packLabelCode 包裝编码
     * @param deliveryOrderCode 签收单号
     */
    @GetMapping("/scanLable")
    public JsonResult scanLable(@RequestParam("packLabelCode")String packLabelCode,@RequestParam("deliveryOrderCode")String deliveryOrderCode){
        OrderDeliveryVO orderDeliveryVO = orderDeliveryService.scanLable(packLabelCode,deliveryOrderCode);
        return JsonResult.success(orderDeliveryVO);
    }
    /**
     * 入库
     */



}
